<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--<el-form-item label="表头Id" prop="headerId">-->
      <!--  <el-input-->
      <!--    v-model="queryParams.headerId"-->
      <!--    placeholder="请输入表头Id"-->
      <!--    clearable-->
      <!--    @keyup.enter.native="handleQuery"-->
      <!--  />-->
      <!--</el-form-item>-->
      <el-form-item label="物品名称" prop="inventoryName">
        <el-input
          v-model="queryParams.inventoryName"
          placeholder="请输入物品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="借出状态" prop="lendStatus">
        <el-select v-model="queryParams.lendStatus" placeholder="请选择借出状态:0借出1归还" clearable>
          <el-option
            v-for="dict in dict.type.ware_borrow_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="借出时间">
        <el-date-picker
          v-model="daterangeLendTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="借出人" prop="lendPeople">
        <el-input
          v-model="queryParams.lendPeople"
          placeholder="请输入借出人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="归还人" prop="returnPeople">
        <el-input
          v-model="queryParams.returnPeople"
          placeholder="请输入归还人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="归还时间">
        <el-date-picker
          v-model="daterangeReturnTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['warehouse:RyLendingReturnRecord:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['warehouse:RyLendingReturnRecord:edit']"
        >修改
        </el-button>
      </el-col>
      <!--<el-col :span="1.5">-->
      <!--  <el-button-->
      <!--    type="danger"-->
      <!--    plain-->
      <!--    icon="el-icon-delete"-->
      <!--    size="mini"-->
      <!--    :disabled="multiple"-->
      <!--    @click="handleDelete"-->
      <!--    v-hasPermi="['warehouse:RyLendingReturnRecord:remove']"-->
      <!--  >删除-->
      <!--  </el-button>-->
      <!--</el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['warehouse:RyLendingReturnRecord:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="RyLendingReturnRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!--<el-table-column label="主键" align="center" prop="id"/>-->
      <el-table-column label="物品名称" align="center" prop="inventoryName"/>
      <el-table-column label="所在仓库" align="center" prop="depotName"/>
      <el-table-column label="可用数量" align="center" prop="currentNumber"/>
      <el-table-column label="借出数量" align="center" prop="lendNum"/>
      <el-table-column label="借出人" align="center" prop="lendPeople"/>
      <el-table-column label="借出时间" align="center" prop="lendTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lendTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归还人" align="center" prop="returnPeople"/>
      <el-table-column label="预计归还时间" align="center" prop="expectedReturnTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expectedReturnTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="归还时间" align="center" prop="returnTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column label="归还数量" align="center" prop="returnNum"/>-->
      <el-table-column label="已归还数量" align="center" prop="returnedQuantity"/>
      <el-table-column label="借出状态" align="center" prop="lendStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ware_borrow_status" :value="scope.row.lendStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['warehouse:RyLendingReturnRecord:edit']"
          >修改
          </el-button>
          <!--<el-button-->
          <!--  size="mini"-->
          <!--  type="text"-->
          <!--  icon="el-icon-delete"-->
          <!--  @click="handleDelete(scope.row)"-->
          <!--  v-hasPermi="['warehouse:RyLendingReturnRecord:remove']"-->
          <!--&gt;删除-->
          <!--</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改借出归还记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!--<el-form-item label="表头Id" prop="headerId">-->
        <!--  <el-input v-model="form.headerId" placeholder="请输入表头Id" :disabled="this.form.id!=null?true:false"/>-->
        <!--</el-form-item>-->
        <el-form-item label="工具名" prop="inventoryId">
          <el-select v-model="form.inventoryId" @change="onSelectedInventory" placeholder="请选择工具"
                     :disabled="this.form.id!=null?true:false"  filterable clearable>
            <el-option
              v-for="item in allInventory"
              :key="item.inventoryId"
              :label="item.inventFirstLetter + ' - ' + item.inventoryName"
              :value="item.inventoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="depotName">
          <el-select v-model="form.depotId" placeholder="请选择仓库" :disabled="this.form.id!=null?true:false">
            <el-option
              v-for="item in allDepot"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="借出时间" prop="lendTime" >-->
        <!--  <el-date-picker clearable-->
        <!--                  v-model="form.lendTime"-->
        <!--                  type="date"-->
        <!--                  value-format="yyyy-MM-dd"-->
        <!--                  placeholder="请选择借出时间" :disabled="this.form.id!=null?true:false">-->
        <!--  </el-date-picker>-->
        <!--</el-form-item>-->
        <el-form-item label="可用数量" prop="currentNumber">
          <el-input v-model="form.currentNumber" placeholder="可用数量" :disabled="true"/>
        </el-form-item>
        <el-form-item label="借出数量" prop="lendNum">
          <el-input v-model.number="form.lendNum" placeholder="请输入借出数量" @blur="onSelectNumber"
                    :disabled="this.form.id!=null?true:false"/>
        </el-form-item>
        <el-form-item label="借出人" prop="lendPeople">
          <el-input v-model="form.lendPeople" placeholder="请输入借出人" :disabled="this.form.id!=null?true:false"/>
        </el-form-item>
        <el-form-item label="预计归还时间" prop="expectedReturnTime">
          <el-date-picker clearable
                          v-model="form.expectedReturnTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择预计归还时间" :disabled="this.form.id!=null?true:false">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="已归还数量" prop="returnedQuantity" v-if="this.form.id != null">
          <el-input v-model="form.returnedQuantity" placeholder="已归还数量" :disabled="this.form.id!=null?true:false"/>
        </el-form-item>
        <el-form-item label="归还数量" prop="returnNum" v-if="this.form.id != null">
          <el-input v-model.number="form.returnNum" placeholder="请输入归还数量" @blur="onSelectNumber"/>
        </el-form-item>
        <el-form-item label="归还人" prop="returnPeople" v-if="this.form.id != null">
          <el-input v-model="form.returnPeople" placeholder="请输入归还人"/>
        </el-form-item>
        <!--<el-form-item label="归还时间" prop="returnTime" v-if="this.form.id != null">-->
        <!--  <el-date-picker clearable-->
        <!--                  v-model="form.returnTime"-->
        <!--                  type="date"-->
        <!--                  value-format="yyyy-MM-dd"-->
        <!--                  placeholder="请选择归还时间">-->
        <!--  </el-date-picker>-->
        <!--</el-form-item>-->
        <el-form-item label="借出状态">
          <el-radio-group v-model="form.lendStatus">
            <el-radio
              v-for="dict in dict.type.ware_borrow_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRyLendingReturnRecord,
  getRyLendingReturnRecord,
  delRyLendingReturnRecord,
  addRyLendingReturnRecord,
  updateRyLendingReturnRecord,
  updateInventoryCurrenStock
} from "@/api/warehouse/RyLendingReturnRecord";
import {getInfoByDepotInventoryId, getInventoryByDepotId} from "@/api/warehouse/WareCurrentStock";

export default {
  name: "RyLendingReturnRecord",
  dicts: ['ware_borrow_status'],
  data() {
    return {
      //所有仓库
      allDepot: [{
        id: 2,
        name: '工具库'
      }],
      //暂时存放库存与借出结果
      num: null,
      num1: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //所有物品
      allInventory: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 借出归还记录表格数据
      RyLendingReturnRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 预计归还时间时间范围
      daterangeLendTime: [],
      // 预计归还时间时间范围
      daterangeReturnTime: [],
      //仓库中物品信息查询参数
      params: {
        depotId: null,
        inventoryId: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        headerId: null,
        inventoryId: null,
        lendStatus: null,
        lendTime: null,
        lendPeople: null,
        returnTime: null,
        returnPeople: null,
        inventoryName: null,
        returnedQuantity: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        inventoryId: [
          {required: true, message: "物品Id不能为空", trigger: "blur"}
        ],
        depotId: [
          {required: true, message: "仓库ID不能为空", trigger: "blur"}
        ],
        lendStatus: [
          {required: true, message: "借出状态:0借出1归还不能为空", trigger: "blur"}
        ],
        lendTime: [
          {required: true, message: "借出时间不能为空", trigger: "blur"}
        ],
        lendNum: [
          {required: true, message: "借出数量不能为空", trigger: "blur"},
          {type: "number", message: "必须为数字", trigger: "blur"}
        ],
        lendPeople: [
          {required: true, message: "借出人不能为空", trigger: "blur"}
        ],
        currentNumber: [
          {required: true, message: "库存不能为空", trigger: "blur"}
        ],
        depotName: [
          {required: true, message: "库存不能为空", trigger: "blur"}
        ],
        returnNum: [
          {required: true, message: "归还数量不能为空", trigger: "blur"},
          {type: "number", message: "归还数量必须为数字", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.allRyInventory();
  },
  methods: {
    //根据仓库id和物品id查询仓库中此物品基本信息和当前数量
    onSelectedInventory(val) {//这里的val是物品id
      console.log("params: " + val + " | " + this.form.depotId);
      this.params.depotId = this.form.depotId;
      this.params.inventoryId = val;
      getInfoByDepotInventoryId(this.params).then(response => {
        console.log(response.data);
        let resultData = {
          depotId: this.form.depotId,
          inventoryId: this.form.inventoryId,
          currentNumber: response.data.currentNumber,
          lockStatus: "0",
        };
        // resultData.depotId = this.form.depotId;
        // resultData.inventoryId = this.form.inventoryId;
        // resultData.remark = null;
        this.form.currentNumber = resultData.currentNumber;
        // console.log(inventoryInfo);
        // this.form.specifications = response.data.specifications;
        // this.form.brand = response.data.brand;
        // this.form.wbs = response.data.wbs;
        // this.form.unitPrice = response.data.unitPrice;

      });
    },
    //判断借出数量和总数量
    onSelectNumber() {
      if (this.form.id) {//判断id是否为空，不为空表示修改
        if (eval(this.form.returnNum) > 0) {//判断归还数量是否大于0
          if (this.form.lendNum >= this.form.returnNum) {//判断借出数量大于归还数量
            if ((this.form.returnedQuantity + this.form.returnNum) <= this.form.lendNum) {//判断归还数量加上已归还数是否
              this.num = eval(this.form.currentNumber) + eval(this.form.returnNum);
            } else {
              this.$message({
                showClose: true,
                message: '警告，归还数量大于借出数量！1',
                type: 'warning'
              });
              this.form.returnNum = null;
            }
          } else {
            this.$message({
              showClose: true,
              message: '警告，归还数量大于借出数量！2',
              type: 'warning'
            });
            this.form.returnNum = null;
          }
        } else {
          this.$message({
            showClose: true,
            message: '警告，请至少归还一个！',
            type: 'warning'
          });
          this.form.returnNum = null;
        }
      } else {//否则表示为空
        if (this.form.currentNumber >= this.form.lendNum) {//如果可用数量小于等于借出数量
          this.num = eval(this.form.currentNumber) - eval(this.form.lendNum);
        } else {
          this.$message({
            showClose: true,
            message: '警告，借出数量大于可用数量！',
            type: 'warning'
          });
          this.form.lendNum = null;
        }
      }

      // if (this.form.currentNumber) {
      //   if (eval(this.form.lendNum) > 0) {
      //     if (eval(this.form.currentNumber) >= eval(this.form.lendNum)) {
      //       if (this.form.id){
      //         if (eval(this.form.returnNum) > 0) {
      //             this.num = eval(this.form.currentNumber) + eval(this.form.returnNum);
      //           // alert(this.num);
      //         } else {
      //           this.$message({
      //             showClose: true,
      //             message: '警告，违规归还，归还数量必须大于0！',
      //             type: 'warning'
      //           });
      //           this.form.returnNum = null;
      //         }
      //       }else{
      //         this.num = eval(this.form.currentNumber) - eval(this.form.lendNum);
      //       }
      //     } else {
      //       this.$message({
      //         showClose: true,
      //         message: '警告，借出数量大于库存数量！',
      //         type: 'warning'
      //       });
      //       this.form.lendNum = null;
      //     }
      //   } else {
      //     this.$message({
      //       showClose: true,
      //       message: '警告，违规借出，借出数量必须大于0！',
      //       type: 'warning'
      //     });
      //     this.form.lendNum = null;
      //   }
      // }
    },
    //根据仓库id查询仓库中物品列表
    allRyInventory() {
      let depotId = 2;//工具库id为2
      getInventoryByDepotId(depotId).then(response => {
        this.allInventory = response.data;
      });
    },
    /** 查询借出归还记录列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeLendTime && '' != this.daterangeLendTime) {
        this.queryParams.params["beginLendTime"] = this.daterangeLendTime[0];
        this.queryParams.params["endLendTime"] = this.daterangeLendTime[1];
      }
      if (null != this.daterangeReturnTime && '' != this.daterangeReturnTime) {
        this.queryParams.params["beginReturnTime"] = this.daterangeReturnTime[0];
        this.queryParams.params["endReturnTime"] = this.daterangeReturnTime[1];
      }
      listRyLendingReturnRecord(this.queryParams).then(response => {
        this.RyLendingReturnRecordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        headerId: 1,
        inventoryId: null,
        remark: null,
        depotId: 2,
        depotName: "工具库",
        lendStatus: "0",
        lendTime: null,
        lendNum: null,
        lendPeople: null,
        expectedReturnTime: null,
        returnTime: null,
        returnNum: null,
        returnPeople: null,
        currentNumber: null,
        returnedQuantity: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeLendTime = [];
      this.daterangeReturnTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加借出归还记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRyLendingReturnRecord(id).then(response => {
        this.allRyInventory();
        this.form = response.data;
        this.form.returnNum = null;
        this.open = true;
        this.title = "修改借出归还记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.num1 = eval(this.form.returnedQuantity) + eval(this.form.returnNum);
      if (eval(this.num1) <= eval(this.form.lendNum)) {
        // alert("12300");
        this.$refs["form"].validate(valid => {//校验
          if (valid) {
            if (this.form.id != null) {//修改数据
              this.form.returnedQuantity = this.num1;
              this.form.currentNumber = this.num;
              updateRyLendingReturnRecord(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {//添加语句方法
              this.form.currentNumber = this.num;
              this.form.returnedQuantity = 0;
              addRyLendingReturnRecord(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });

      } else {//提示
        this.$message({
          showClose: true,
          message: '警告，归还数量大于借出数量！',
          type: 'warning'
        });
        this.form.returnNum = null;
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除借出归还记录编号为"' + ids + '"的数据项？').then(function () {
        return delRyLendingReturnRecord(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('warehouse/RyLendingReturnRecord/export', {
        ...this.queryParams
      }, `RyLendingReturnRecord_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
